package com.dataconver.scheduler;

import com.dataconver.sync.DataSynchronizer;
import com.dataconver.sync.SyncResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 定时同步调度器
 * 支持定时自动同步和手动按键同步
 * 使用Spring Boot的@Scheduled注解实现定时任务
 */
@Component
public class SyncScheduler {
    private static final Logger logger = LoggerFactory.getLogger(SyncScheduler.class);
    
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private final Scanner scanner = new Scanner(System.in);
    
    @Autowired
    private DataSynchronizer dataSynchronizer;
    
    // 从配置文件读取cron表达式
    @Value("${sync.cron:0 0 8 * * ?}")
    private String cronExpression;
    
    /**
     * 启动定时同步
     * 使用Spring Boot的@Scheduled注解，无需手动管理Quartz
     */
    public void startScheduledSync() {
        logger.info("🔄 启动定时同步调度器...");
        logger.info("📅 配置的定时表达式: {}", cronExpression);
        
        // 启动手动同步监听
        if (isRunning.compareAndSet(false, true)) {
            startManualSyncListener();
        }
    }
    
    /**
     * 定时同步任务
     * 使用Spring Boot的@Scheduled注解，cron表达式从配置文件读取
     */
    @Scheduled(cron = "${sync.cron:0 0 8 * * ?}")
    public void scheduledSync() {
        LocalDateTime now = LocalDateTime.now();
        String timeStr = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        logger.info("⏰ 定时同步任务开始执行 - 当前时间: {}", timeStr);
        logger.info("📅 执行时间: {}", cronExpression);

        try {
            SyncResult result = dataSynchronizer.syncAll();
            
            if (result.isSuccess()) {   
                logger.info("✅ 定时同步成功 - 处理: {} 条, 插入: {} 条, 更新: {} 条", 
                    result.getProcessedRows(), result.getInsertedRows(), result.getUpdatedRows());
            } else {
                logger.error("❌ 定时同步失败: {}", result.getErrorMessage());
            }
            
        } catch (Exception e) {
            logger.error("❌ 定时同步执行异常", e);
        }
        
        logger.info("⏰ 定时同步任务执行完成 - 结束时间: {}", 
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }
    
    /**
     * 启动手动同步监听
     */
    public void startManualSyncListener() {
        Thread manualSyncThread = new Thread(() -> {
    
            
            while (isRunning.get()) {
                try {
                    if (System.in.available() > 0) {
                        String input = scanner.nextLine().trim().toLowerCase();
                        if ("s".equals(input)) {
            
                            executeManualSync();
                        } else if ("q".equals(input)) {
            
                            isRunning.set(false);
                            break;
                        }
                    }
                    Thread.sleep(100);
                } catch (Exception e) {
                    logger.error("手动同步监听异常", e);
                }
            }
        });
        
        manualSyncThread.setDaemon(true);
        manualSyncThread.start();
    }
    
    /**
     * 执行手动同步
     */
    public void executeManualSync() {
        try {
            SyncResult result = dataSynchronizer.syncAll();
            
                    if (result.isSuccess()) {
            logger.info("✅ 手动同步成功 - 处理: {} 条, 插入: {} 条, 更新: {} 条", 
                result.getProcessedRows(), result.getInsertedRows(), result.getUpdatedRows());
        } else {
            logger.error("手动同步失败: {}", result.getErrorMessage());
        }
            
        } catch (Exception e) {
            logger.error("执行手动同步时发生异常", e);
        }
    }
}
